package com.ruoyi.wxapidaily;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.wx.domain.ADaily;
import com.ruoyi.wx.domain.ALikes;
import com.ruoyi.wx.domain.AWxuser;
import com.ruoyi.wx.service.IADailyService;
import com.ruoyi.wx.service.IALikesService;
import com.ruoyi.wx.service.IAWxuserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
/**
 * author：pan
 * 微信小程序  对用户上传的日常进行 /保存 / 分页查询 / 左右分页查询 / 按时间段查询
 *
 */

@RestController
@RequestMapping("/wxapi")
public class WxUserUploadDailyController {

    @Autowired
    private IADailyService dailyService;

    @Autowired
    private IAWxuserService wxuserService;

    @Autowired
    private IALikesService likesService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 获取到前端传来的 日常数据 加工并保存
     * @param aDaily
     * @return
     */
    @PostMapping("/uploadDaily")
    public AjaxResult uploadDaily(@RequestBody ADaily aDaily){

        // 用户的openid
        String openid = aDaily.getOpenid();

        // 1、判断用户的openid  判断用户是否存在
        AWxuser wxuser = wxuserService.selectWxuserOpenID(openid);

        if(wxuser == null){
            return AjaxResult.error("上传失败");
        }

        // 2、判断用户是否被禁用
        String isNormal  = wxuser.getSituation();
        if(isNormal.equals("禁用")){
            return AjaxResult.error("该用户已被禁用，请联系管理员！");
        }

        // 3、添加额外信息
        aDaily.setCatCheck("审核中");
        aDaily.setCatChoice("审核中");

        // 4、保存数据
        dailyService.insertADaily(aDaily);

        return AjaxResult.success("上传成功！");
    }
// @PathVariable Integer pageNum, @PathVariable Integer pageSize, @PathVariable String openid


    /**
     * 日常 分页查询 左边与右边
     * @return
     */
    public ArrayList<ADaily> getdailyList(Integer pageNum, Integer pageSize, Integer isLoad){

        ArrayList<ADaily> aDailies = new ArrayList<>();

        // 左边查询
        if(isLoad == 0){
            aDailies = dailyService.getDailiesList(pageNum, pageSize);   // 通过
        }

        // 右边查询
        if(isLoad == 1){
            aDailies = dailyService.getChoiceList(pageNum, pageSize);   // 精选
        }
        return aDailies;
    }



    /**
     * 从缓存拿分页数据，判断用户是否点赞
     * @return
     */
    @PostMapping("/loadDaily")
    public AjaxResult loadDaily(@RequestBody JSONObject object){
        try {
            Integer isLoad = (Integer)object.get("isLoad");

            Integer pageNum = (Integer)object.get("pageNum");     // 获取 pageNum
            Integer pageSize = (Integer)object.get("pageSize");   // 获取 pageSize
            String openid = (String)object.get("openid");         // 获取 openid

            // 获取分页数据
            ArrayList<ADaily> aDailies = getdailyList(pageNum, pageSize, isLoad);

            // 获取喜欢数据
            List<ALikes> alikes = loadLikes();

            // 同时查看是否点赞
            for (ADaily daily : aDailies){
                long dailyId = daily.getId();  // 获取评论id
                for (ALikes like : alikes){

                    long likeDailyId = like.getDailyId();    // 获取like表中的 评论id
                    String likeopenid = like.getOpenid();    // 获取like表中的 openid

                    if(likeDailyId == dailyId && likeopenid.equals(openid)){
                        daily.setRemark("已点赞");
//                        System.out.println(likeDailyId + ":" + likeopenid + "已点赞");
                    }
                }
                daily.setOpenid("null");  // 不让用户看见openid
            }

            return AjaxResult.success("查询成功！", aDailies);

        }catch (Exception e){
            return AjaxResult.error("查询失败！",e);
        }
    }

//     @Cacheable(value = "loadLikes", key = "'likes'", cacheManager = "redisExpire")
    /**
     * 获取点赞列表 永久缓存点赞列表
     * @return
     */
    public List<ALikes> loadLikes(){
        // Redis的key
        String key = "cat:like:loadLikes";

        // 去Redis缓存中查找
        String likeListJson = redisTemplate.opsForValue().get(key);

        // 如果缓存中存在
        if(StrUtil.isNotBlank(likeListJson)){

            //将数据转换
            List<ALikes> alikes = JSONUtil.toList(likeListJson, ALikes.class);

            //这里就不进行缓存时间更新了【已设置 永不过期】
            //直接返回数据
            return alikes;
        }

        // 如果没有则进数据库去查找
        List<ALikes> alikes = likesService.getLikesList();

        // 将数据存入Redis中【这里就不设置过期时间了】
        // redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(aCatList), 30, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(alikes));

        return alikes;
    }

    /**
     * 用户点赞功能
     * @param aLikes
     * @return
     */
    @PostMapping("/userLikes")
    public AjaxResult userLikes(@RequestBody ALikes aLikes){

        try{
            String openid = aLikes.getOpenid();        // 获取 openid

            // 1、判断用户的openid  判断用户是否存在
            if(StrUtil.isBlank(openid)){
                return AjaxResult.error("点赞失败");
            }

            AWxuser wxuser = wxuserService.selectWxuserOpenID(openid);

            if(wxuser == null){
                return AjaxResult.error("用户未登录，点赞失败");
            }

            // 2、判断用户是否被禁用
            String isNormal  = wxuser.getSituation();
            if(isNormal.equals("禁用")){
                return AjaxResult.error("该用户已被禁用，请联系管理员！");
            }

            // 3、 查询 评论条数是否存在   点赞数+1
            ADaily aDaily = dailyService.selectADailyById(aLikes.getDailyId());
            if (aDaily == null){
                return AjaxResult.error("未查询到该评论，点赞失败");
            }

            Long likes = aDaily.getCatLikes();
            aDaily.setCatLikes(likes+1);         // 点赞数+1

            dailyService.updateADaily(aDaily);   // 更新数据


            // 4. 点赞表 数据数据 插入
            likesService.insertALikes(aLikes);


            return AjaxResult.success("点赞成功！");
        }catch (Exception e){
            return AjaxResult.error("点赞失败！",e);
        }
    }


    /**
     * 根据id从缓存拿数据 并判断是否点赞
     * @param object
     * @return
     */
    @PostMapping("/loadCatDailyInfo")
    public AjaxResult loadCatDailyInfo(@RequestBody JSONObject object){
        try {

            Integer catId = (Integer)object.get("catId");          // 获取 catId
            Integer pageNum = (Integer)object.get("pageNum");     // 获取 pageNum
            Integer pageSize = (Integer)object.get("pageSize");   // 获取 pageSize
            String openid = (String)object.get("openid");         // 获取 openid

            // 获取分页数据
            ArrayList<ADaily> aDailies = getCatIdList(pageNum, pageSize, catId);   // 通过id 查询

            // 获取喜欢数据
            List<ALikes> alikes = loadLikes();

            // 创建一个新数组
            ArrayList<ADaily> list = new ArrayList<>();

            // 同时查看是否点赞
            for (ADaily daily : aDailies){
                long dailyId = daily.getId();  // 获取评论id
                for (ALikes like : alikes){

                    long likeDailyId = like.getDailyId();    // 获取like表中的 评论id
                    String likeopenid = like.getOpenid();    // 获取like表中的 openid

                    if(likeDailyId == dailyId && likeopenid.equals(openid)){
                        daily.setRemark("已点赞");
                    }
                }
                daily.setOpenid("null");  // 不让用户看见openid

                // 添加到新数组中
                list.add(daily);
            }

            return AjaxResult.success("查询成功！", list);
        }catch (Exception e){
            return AjaxResult.error("查询失败！", e);
        }
    }

    /**
     * 分页  根据id查
     * @param pageNum
     * @param pageSize
     * @param catId
     * @return
     */
    public ArrayList<ADaily> getCatIdList(Integer pageNum, Integer pageSize, Integer catId){
        ArrayList<ADaily> aDailies = dailyService.getCatIdList(pageNum, pageSize, catId);   // 通过id 查询

        return aDailies;
    }

    /**
     * 日常 按时间段查询
     * @return
     */
    @PostMapping("/loadSelectTimeDaily")
    public ArrayList<ADaily> loadSelectTimeDaily(@RequestBody JSONObject object){

        Integer year = (Integer)object.get("year");          // 获取 catId
        Integer month = (Integer)object.get("month");     // 获取 pageNum

        ArrayList<ADaily> aDailies = new ArrayList<>();
        if (year == null || month == null) {
            throw new IllegalArgumentException("Year and month must not be null");
        }

        String formattedMonth = String.format("%02d", month);
        String time = year + "-" + formattedMonth + "-01";

        // 构造开始时间和结束时间
        String startTime = DateUtil.beginOfMonth(DateUtil.parseDate(time)).toDateStr();
        String endTime = DateUtil.endOfMonth(DateUtil.parseDate(time)).toDateStr();


        aDailies = dailyService.loadSelectTimeDaily(startTime, endTime);   // 时间段查询


        return aDailies;
    }


}


